package com.example.bysj.Dao;

//201902104061徐中堂
import com.example.bysj.domain.*;

import com.example.bysj.Service.DepartmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
//声明数据库访问类
@Repository("teacherDao")
public class TeacherDao {
    //自动注入
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DepartmentService departmentService;

    //增加老师
    public boolean add(Teacher teacher) {
        String sql = "INSERT INTO teacher (no,name,department_id) VALUES (?,?,?,)";
        int affectedRowNum = jdbcTemplate.update(sql, teacher.getNo(),teacher.getName(),
               teacher.getDepartment().getId()
        );
        if (affectedRowNum != 1) {
            return false;
        } else {

            return true;
        }
    }

    //通过定义内部类来返回查询结果
    public class TeacherRowMapper implements RowMapper<Teacher> {
        @Override
        public Teacher mapRow(ResultSet resultSet, int i) throws SQLException {
            Teacher teacher = new Teacher();
            teacher.setId(resultSet.getInt("id"));
            teacher.setName(resultSet.getString("name"));
            teacher.setNo(resultSet.getString("no"));

            Department department =
                    departmentService.find(resultSet.getInt("department_id"));
            teacher.setDepartment(department);
            return teacher;
        }
    }
    //查找
    public Teacher find(int id){
        String sql = "SELECT * FROM teacher WHERE id = ?";
        List<Teacher> teachers = jdbcTemplate.query(sql, new Object[]{id}, new TeacherRowMapper());
        if(!teachers.isEmpty()){
            return teachers.get(0);
        } else
            return null;
    }
    //查找全部
    public List<Teacher> findAll(){
        String sql = "SELECT * FROM teacher ";
        List<Teacher> teachers = jdbcTemplate.query(sql,  new TeacherRowMapper());
        return teachers;
    }
    //修改老师
    public boolean update(Teacher teacher){
        String sql = "UPDATE teacher SET no = ? ,name=? WHERE id = ?";
        int affectedRowNum = jdbcTemplate.update(sql,teacher.getNo(),teacher.getName(),teacher.getId());
        if (affectedRowNum!=1){
            return false;
        }else{
            return true;
        }
    }
    //根据id删除
    public boolean delete(int id){
        String sql = "DELETE FROM Teacher WHERE id = ? ";
        int affectedRowNum = jdbcTemplate.update(sql,id);
        if (affectedRowNum!=1){
            return false;
        }else{
            return true;
        }
    }
}
